package com.msb.advanced;

import lombok.Data;

import java.util.LinkedList;
import java.util.List;

public class _03Code02_DeleteGivenValue {

	@Data
	public static class Node {
		public int value;
		public Node next;

		public Node(int data) {
			this.value = data;
		}
	}

	public static Node deleteOne2(Node node, int num) {
		Node first = null;
		Node cur = node;
		while(cur != null) {
			if (cur.value != num) {
				first = cur;
				break;
			}
			cur = cur.next;
		}
		if (first == null) {
			return null;
		}
		Node pre = first;
		Node next = first.next;
		while(next != null) {
			if (next.value != num) {
				pre.next = next;
				pre = next;
			}
			next = next.next;
		}
		pre.next = null;
		return first;
	}
	
	public static Node deleteOne(Node node, int num) {
		LinkedList<Node> list = new LinkedList<>();
		Node cur = node;
		while (cur != null) {
			list.add(cur);
			cur = cur.next;
		}
		list.removeIf(x -> x.value == num);
		if (list.isEmpty()) {
			return null;
		}
		// pop没有是报错的, 都是返回头结点
		Node res = list.pop();
		Node pre = res;
		for(Node curNode : list) {
			pre.next = curNode;
			pre = curNode;
		}
		return res;
	}

	public static void main(String[] args) {
		Node node = new Node(1);
		Node node2 = new Node(1);
		Node node3 = new Node(2);
		node.next = node2;
		node2.next = node3;
		Node node1 = deleteOne2(node, 1);
		System.out.println(node1);
	}
	
	// head = removeValue(head, 2);
	public static Node removeValue(Node head, int num) {
		// head来到第一个不需要删的位置
		while (head != null) {
			if (head.value != num) {
				break;
			}
			head = head.next;
		}
		// 1 ) head == null
		// 2 ) head != null
		Node pre = head;
		Node cur = head;
		while (cur != null) {
			if (cur.value == num) {
				pre.next = cur.next;
			} else {
				pre = cur;
			}
			cur = cur.next;
		}
		return head;
	}

}
